import React, { memo, useEffect, useRef, useState } from 'react';
import {
  ConfigProvider,
  Divider,
  Table,
  Modal,
  Button,
  Form,
  Input,
  Popconfirm,
  Space,
  Dropdown,
  message,
  Drawer,
  Menu,
  Descriptions,
  Col,
  Row
} from 'antd';
import { ProForm } from '@/base-ui';
import DivWrapper from './style';
import zhCN from 'antd/es/locale/zh_CN';
import http from '@/services/request';
import TipsHeader from '@/components/TipsHeader';
import chickenHousePicture from '@/assets/img/chicken-house.png';
import {
  PageSearchConfig,
  SearchSelector,
  DataType,
  UseSearch
} from './config';
//form
const NewForm = (props: any) => {
  return (
    <Form ref={props.newref} layout={'vertical'} style={{ minHeight: '100%', flex: 1, overflow: 'auto', width: '100%', overflowX: 'hidden' }}>
      <Row >
        <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 3 }}>
      <Form.Item
        name="distributionBatchId"
        label="请输入分发批次编号"
        rules={[{ required: true, message: '请输入分发批次编号' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="请输入批次等级"
        name="batchGrade"
        rules={[{ required: true, message: '请输入批次等级' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="请输入批次品种"
        name="batchVariety"
        rules={[{ required: true, message: '请输入批次品种' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="buybackPrice"
        label="请输入回购单价"
        rules={[{ required: true, message: '请输入回购单价' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="buybackQuantity"
        label="请输入回购数量"
        rules={[{ required: true, message: '请输入回购数量' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="totalPrice"
        label="请输入总金额"
        rules={[{ required: true, message: '请输入总金额' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="responsiblePhone"
        label="请输入负责人电话号码"
        rules={[{ required: true, message: '请输入负责人电话号码' }]}
      >
        <Input />
      </Form.Item>
        </Col>
        <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 3 }}>
      <Form.Item
        name="responsibleName"
        label="请输入负责人名字"
        rules={[{ required: true, message: '请输入负责人名字' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="vaccinationStatus"
        label="请输入疫苗接种率"
        rules={[{ required: true, message: '请输入疫苗接种率' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="dayAge"
        label="请输入肉鸡日龄"
        rules={[{ required: true, message: '请输入肉鸡日龄' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="averageWeight"
        label="请输入肉鸡平均体重"
        rules={[{ required: true, message: '请输入肉鸡平均体重' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="coopId"
        label="请输入合作社编号"
        rules={[{ required: true, message: '请输入合作社编号' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="coopName"
        label="请输入合作社名称"
        rules={[{ required: true, message: '请输入合作社名称' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="remark"
        label="请备注"
        rules={[{ required: true, message: '请备注' }]}
      >
        <Input />
      </Form.Item>
        </Col>
      </Row>
    </Form>
  );
};

//按钮组
const Buttongroup = (props: any) => {
  return (
    <div style={{ marginBottom: 10, float: 'left' }}>
      <Button
        type="primary"
        onClick={() => props.add()}
        style={{ marginRight: 10 }}
      >
        新增订单
      </Button>
      <Button
        danger
        onClick={() => {
          props.checkIt();
        }}
        style={{ marginRight: 10 }}
      >
        批量删除
      </Button>


    </div>
  );
};

const BuyBack = memo(() => {
  //复选框的内容设定
  const [selectionType] = useState<'checkbox' | 'radio'>('checkbox');

  //更多功能定位id
  const [Drawerid, setDrawerid]: any = useState({});
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //复选框批量删除
  const [itemSelected, setItemSelected] = useState<React.Key[]>([]);

  //是否新增
  const [edited, setedited]: any = useState('');
  //高级检索
  const [isMoreSearchShow, setisMoreSearchShow]: any = useState(false);
  const newref: any = useRef();
  const [dataSource, setdataSource]: any = useState([]);
  const [searchMore, setSearchMore] = useState(false);

  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);

  useEffect(() => {
    http.get('/feed/chickenBuybackFarming/list/1/30').then((res) => {
      setdataSource(res.data.records);
    });
  }, []);

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[]) => {
      setItemSelected(selectedRowKeys);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  };

  const checkIt = () => {
    http({
      url: `/feed/chickenBuybackFarming/deletion/batch`,
      method: 'delete',
      data: JSON.stringify(itemSelected),
      headers: { 'Content-Type': 'application/json' }
    }).then(() => {
      http.get('/feed/chickenBuybackFarming/list/1/10').then((res) => {
        setdataSource(res.data.records);
      });
    });
  };

  //导出
  const exported = () => {
    http({
      method: 'get',
      url: '/server/dailySlaughter/export',
      data: JSON.stringify([1, 4]),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res: any) => {
      const blob = new Blob([res.data], {
        // res 为后台返回数据
        type: 'application/vnd.ms-excel;charset=utf-8' // 导出数据生成excel的格式设置
      });
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = Date.now() + `.xlsx`;
        elink.style.display = 'none';
        elink.target = '_blank';
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
      }
    });
  };

  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    // 修改操作
    if (edited) {
      const newedited = newref.current.getFieldsValue();
      http
        .put(`/feed/chickenBuybackFarming/update/${edited.id}`, {
          ...newedited
        })
        .then(() => {
          http.get('/feed/chickenBuybackFarming/list/1/10').then((res) => {
            setdataSource(res.data.records);
          });
        });
      setedited(null);
      return;
    }
    //id不在--就是新增
    const addData = newref.current.getFieldsValue();
    const {
      batchId,
      distributionBatchId,
      batchGrade,
      batchVariety,
      buybackPrice,
      buybackQuantity,
      totalPrice,
      responsibleId,
      responsiblePhone,
      responsibleName,
      vaccinationStatus,
      dayAge,
      averageWeight,
      coopId,
      coopName,
      remark
    } = addData;

    http
      .post('/feed/chickenBuybackFarming/save', {
        batchId,
        distributionBatchId,
        batchGrade,
        batchVariety,
        buybackPrice,
        buybackQuantity,
        totalPrice,
        responsibleId,
        responsiblePhone,
        responsibleName,
        vaccinationStatus,
        dayAge,
        averageWeight,
        coopId,
        coopName,
        remark
      })
      .then(() => {
        http.get('/feed/chickenBuybackFarming/list/1/10').then((res) => {
          setdataSource(res.data.records);
        });
      })
      .catch((error) => {
        // eslint-disable-next-line no-console
        console.log(error);
      });
  };

  //编辑
  const edit = (id: any) => {
    setAddModalVisible(true);
    //这里必须单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
    setTimeout(() => {
      newref.current.setFieldsValue({
        ...id
      });
      setedited(id);
    }, 0);
  };

  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    setTimeout(() => {
      newref.current.setFieldsValue({
        repoId: '',
        batchNumber: '',
        productName: '',
        matName: '',
        supplier: '',
        money: '',
        cases: '',
        quantity: '',
        weight: '',
        unit: ''
      });
    });
    setAddModalVisible(true);
  };

  const indexTable = {
    pagination: {
      //每页 10 条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //当前的页数和大小
      onShowSizeChange: (current: any, pageSize: any) => {},
      //自定义每页显示项目的选项
      pageSizeOptions: ['5', '10', '15'],

      // 输入指定页码跳页
      showQuickJumper: true,
      //跳页之后的回调函数
      onShowQuickJump: (page: any) => {},
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length,
      // 改变的回调函数
      onChange: (page: any) => {}
    }
  };

  const FormColumns: any = [
    {
      title: '批次编号',
      dataIndex: 'batchId',
      key: 'batchId',
      width: 100
    },
    {
      title: '分发批次编号',
      dataIndex: 'distributionBatchId',
      key: 'distributionBatchId',
      width: 120
    },
    {
      title: '批次等级',
      dataIndex: 'batchGrade',
      key: 'batchGrade',
      width: 100
    },
    {
      title: '批次品种',
      dataIndex: 'batchVariety',
      key: 'batchVariety',
      width: 100
    },
    {
      title: '回购单价',
      dataIndex: 'buybackPrice',
      key: 'buybackPrice',
      width: 100
    },
    {
      title: '回购数量',
      dataIndex: 'buybackQuantity',
      key: 'buybackQuantity',
      width: 100
    },
    {
      title: '总金额',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      width: 100
    },
    {
      title: '合作社名称',
      dataIndex: 'coopName',
      key: 'coopName',
      width: 100
    },
    {
      title: '负责人名称',
      dataIndex: 'responsibleName',
      key: 'responsibleName',
      width: 120
    },
    {
      title: '负责人电话',
      dataIndex: 'responsiblePhone',
      key: 'responsiblePhone',
      width: 120
    },
    {
      title: '疫苗接种情况',
      dataIndex: 'vaccinationStatus',
      key: 'vaccinationStatus',
      width: 120
    },
    {
      title: '肉鸡日龄',
      dataIndex: 'dayAge',
      key: 'dayAge',
      width: 100
    },
    {
      title: '肉鸡平均体重',
      dataIndex: 'averageWeight',
      key: 'averageWeight',
      width: 120
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => (
        <Space>
          <a onClick={() => edit(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            onConfirm={() => {
              http
                .delete(`/feed/chickenBuybackFarming/delete/${record.id}`)
                .then(() => {
                  const newData = dataSource.filter(
                    (item: { id: any }) => item.id !== record.id
                  );
                  setdataSource(newData);
                });
            }}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            <a
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              ···
            </a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];

  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={() => {
                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },
        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );

  // 高级检索的函数
  const onFinish = (form: any) => {
    // 发送请求
    // console.log(form)
    // form.buybackTime = form.buybackTime?.format('YYYY-MM-DD')
    http.post('/feed/chickenBuybackFarming/get', form).then((res: any) => {
      if (res.statusCode !== 20000) {
        return message.error('查询失败');
      }
      const data = res.data || [];
      setdataSource(data);
    });
  };
  //详情--抽屉
  const showDrawer = (data: any) => {
    setDrawerVisible(true);
    http.get(`/feed/chickenBuybackFarming/get/${data.id}`).then((res) => {
      setDrawerid(res.data);
    });
  };

  const onDraweClose = () => {
    setDrawerVisible(false);
  };

  const renderDescription = () => (
    <p>肉鸡回购是指在鸡只生长周期结束后，以一定价格回购鸡只。肉鸡回购有利于肉鸡养殖企业的经济利益，通过回购控制肉鸡的销售渠道，提高销售收入。同时，肉鸡回购也能够确保养殖户的利益，减少销售中的风险和损失，促进良性的养殖生态。肉鸡回购通常会根据鸡只品种、鸡只数量、鸡只质量和市场行情等因素来进行定价。在回购过程中，需要注意鸡只的安全运输、交易凭证的签署、鸡只数量和质量的检验等方面，以确保交易的公正、公平、安全和合法。</p>
  )

  return (
    <DivWrapper>
      <TipsHeader imgSrc={chickenHousePicture} title="肉鸡回购" description={renderDescription()} />
      {searchMore && (
        <div>
          <ProForm formItems={PageSearchConfig} onFinish={onFinish} />
          <Divider style={{ margin: '10px 0 20px' }} />
        </div>
      )}
      <Buttongroup
        checkIt={() => checkIt()}
        add={() => add()}
        exported={() => exported()}
      />
      <UseSearch
        setisMoreSearchShow={(e: any) => {
          setisMoreSearchShow(e);
        }}
        isMoreSearchShow={isMoreSearchShow}
        setsearchMore={(e: boolean) => setSearchMore(e)}
      />
      <SearchSelector
        dataSource={(e: any) => setdataSource(e)}
      ></SearchSelector>
      <ConfigProvider locale={zhCN}>
        <Table
          dataSource={dataSource}
          columns={FormColumns}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          rowKey={(i) => i.id}
          rowSelection={{
            type: selectionType,
            ...rowSelection
          }}
        />
      </ConfigProvider>
      <Drawer
        title="详情"
        placement="right"
        size="large"
        onClose={onDraweClose}
        visible={DrawerVisible}
      >
        <Descriptions
          title={`订单编号：${Drawerid.id}`}
          bordered
          style={{ width: '450px' }}
        >
          <Descriptions.Item label="合作社编号">
            {Drawerid.coopId}
          </Descriptions.Item>
          <Descriptions.Item label="合作社名称">
            {Drawerid.coopName}
          </Descriptions.Item>
          <Descriptions.Item label="批次编号">
            {Drawerid.batchId}
          </Descriptions.Item>
          <Descriptions.Item label="分发批次编号">
            {Drawerid.distributionBatchId}
          </Descriptions.Item>
          <Descriptions.Item label="批次等级">
            {Drawerid.batchGrade}
          </Descriptions.Item>
          <Descriptions.Item label="批次品种">
            {Drawerid.batchVariety}
          </Descriptions.Item>
          <Descriptions.Item label="总金额">
            {Drawerid.totalPrice}
          </Descriptions.Item>
          <Descriptions.Item label="回购数量">
            {Drawerid.buybackQuantity}
          </Descriptions.Item>
          <Descriptions.Item label="负责人名字">
            {Drawerid.responsibleName}
          </Descriptions.Item>
          <Descriptions.Item label="负责人ID">
            {Drawerid.responsibleId}
          </Descriptions.Item>
          <Descriptions.Item label="负责人电话">
            {Drawerid.responsiblePhone}
          </Descriptions.Item>
          <Descriptions.Item label="疫苗接种率">
            {Drawerid.vaccinationStatus}
          </Descriptions.Item>
          <Descriptions.Item label="肉鸡日龄">
            {Drawerid.dayAge}
          </Descriptions.Item>
          <Descriptions.Item label="平均重量">
            {Drawerid.averageWeight}
          </Descriptions.Item>
          <Descriptions.Item label="备注">{Drawerid.remark}</Descriptions.Item>
        </Descriptions>
      </Drawer>
      <Modal
        width={'600px'}
        centered
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column-reverse',
        }}
        title="新增订单"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <NewForm newref={newref} />
      </Modal>
    </DivWrapper>
  );
});
export default BuyBack;
